package com.cocos.game

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import cn.thinkingdata.analytics.TDAnalytics
import cn.thinkingdata.analytics.TDConfig
import cn.thinkingdata.thirdparty.TDThirdPartyType
import com.cocos.service.SDKWrapper.SDKInterface
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.json.JSONException
import org.json.JSONObject
import java.util.Date


class ThinkingCocosSDK : SDKInterface {

    companion object {
        @SuppressLint("StaticFieldLeak")
        var instance: ThinkingCocosSDK? = null
        private const val TAG = "ThinkingCocosSDK"

        private val developer_devices = listOf("039bf5ef49752a55")
    }

    var activity: Activity? = null

    var appid = "0bdaf63f4a1f4b04b54b17db6572edc7"
    var url = "https://rtsyx.higgsyx.com"

    var distinctId: String? = null
    var deviceId: String? = null

    override fun init(context: Context?) {
        this.activity = context as Activity
        Log.i(TAG, "init: $TAG")
        instance = this

        JsbSDK.onMsg("ThinkingCocosSDK.login") { args -> this.login(args) }
        JsbSDK.onMsg("ThinkingCocosSDK.setSuperProperties") { args -> this.setSuperProperties(args) }
        JsbSDK.onMsg("ThinkingCocosSDK.track") { args -> this.track(args) }
        JsbSDK.onMsg("ThinkingCocosSDK.userSetOnce") { args -> this.userSetOnce(args) }
        JsbSDK.onMsg("ThinkingCocosSDK.userAdd") { args -> this.userAdd(args) }

        initialize()
    }

    private fun initialize() {
        Log.i(TAG, "initialize: ")
        this.deviceId = MiscSDK.instance?.getDeviceId()
        Log.i(TAG, "misc getDeviceId: ${this.deviceId}")

        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        TDAnalytics.enableLog(false)
        var config = TDConfig.getInstance(this.activity, appid, url)
        TDAnalytics.init(config)
        TDAnalytics.enableAutoTrack(TDAnalytics.TDAutoTrackEventType.APP_START or TDAnalytics.TDAutoTrackEventType.APP_END or TDAnalytics.TDAutoTrackEventType.APP_INSTALL)

    }

    private fun login(args: String) {
        Log.i(TAG, "login: $args");
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        val argMap: Map<String, Any> = Gson().fromJson(args, object : TypeToken<Map<String, Any>>() {}.type);
        val uid = argMap["uid"] as? String
        TDAnalytics.login(uid)
        TDAnalytics.enableThirdPartySharing(TDThirdPartyType.APPS_FLYER)

        this.distinctId = TDAnalytics.getDistinctId()
        AppsFlyerCocosSDK.instance?.setCustomerId(this.distinctId!!)
    }

    private fun setSuperProperties(args: String) {
        Log.i(TAG, "setSuperProperties: $args")
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        try {
            val jsonObject = JSONObject(args)
            TDAnalytics.setSuperProperties(jsonObject)
        } catch (e: JSONException) {
            Log.e(TAG, "Failed to parse JSON: $args", e)
        }
    }

    private fun track(args: String) {
        Log.i(TAG, "track: $args")
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        try {
            val jsonObject = JSONObject(args)
            val eventName = jsonObject.optString("_track_event_name").takeIf { it.isNotEmpty() }
            eventName?.let {
                jsonObject.remove("_track_event_name")
                TDAnalytics.track(it, jsonObject)
            } ?: Log.e(TAG, "Missing event name in tracking data")
        } catch (e: JSONException) {
            Log.e(TAG, "Failed to parse JSON: ${e.message}")
        }
    }

    private fun userSet(args: String) {
        Log.i(TAG, "userSet: $args")
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        try {
            val jsonObject = JSONObject(args)
            // 遍历处理含日期前缀的字段
            val dateKeys = mutableListOf<String>()
            val keysIterator = jsonObject.keys()
            // 第一阶段：收集需要处理的键
            while (keysIterator.hasNext()) {
                keysIterator.next().takeIf { it.startsWith("__date__") }?.let {
                    dateKeys.add(it)
                }
            }
            // 第二阶段：处理日期转换
            dateKeys.forEach { key ->
                try {
                    val timestamp = jsonObject.getLong(key) // 获取原始时间戳
                    val newKey = key.removePrefix("__date__") // 生成新键名

                    // 时间戳转 Date 对象（假设原始时间戳为毫秒）
                    val date = Date(timestamp)

                    // 替换字段（Android 的 JSONObject 支持直接存储 Date 类型）
                    jsonObject.remove(key)
                    jsonObject.put(newKey, date)
                } catch (e: JSONException) {
                    Log.e(TAG, "Invalid timestamp format for key [$key]", e)
                }
            }
            TDAnalytics.userSet(jsonObject)
        } catch (e: JSONException) {
            Log.e(TAG, "Failed to parse JSON: ${e.message}")
        }
    }

    private fun userSetOnce(args: String) {
        Log.i(TAG, "userSetOnce: $args")
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        try {
            val jsonObject = JSONObject(args)
            // 遍历处理含日期前缀的字段
            val dateKeys = mutableListOf<String>()
            val keysIterator = jsonObject.keys()
            // 第一阶段：收集需要处理的键
            while (keysIterator.hasNext()) {
                keysIterator.next().takeIf { it.startsWith("__date__") }?.let {
                    dateKeys.add(it)
                }
            }
            // 第二阶段：处理日期转换
            dateKeys.forEach { key ->
                try {
                    val timestamp = jsonObject.getLong(key) // 获取原始时间戳
                    val newKey = key.removePrefix("__date__") // 生成新键名

                    // 时间戳转 Date 对象（假设原始时间戳为毫秒）
                    val date = Date(timestamp)

                    // 替换字段（Android 的 JSONObject 支持直接存储 Date 类型）
                    jsonObject.remove(key)
                    jsonObject.put(newKey, date)
                } catch (e: JSONException) {
                    Log.e(TAG, "Invalid timestamp format for key [$key]", e)
                }
            }
            TDAnalytics.userSetOnce(jsonObject)
        } catch (e: JSONException) {
            Log.e(TAG, "Failed to parse JSON: ${e.message}")
        }
    }

    private fun userAdd(args: String) {
        Log.i(TAG, "userAdd: $args")
        if (developer_devices.contains(MiscSDK.instance?.getDeviceId().toString())) return
        try {
            val jsonObject = JSONObject(args)
            TDAnalytics.userAdd(jsonObject)
        } catch (e: JSONException) {
            Log.e(TAG, "Failed to parse JSON: ${e.message}")
        }
    }
}